<template>
    <el-form :model="userData" label-width="120px" class="user-login-form">
        <div class="form-content">
            <el-form-item>
                <el-text class="mx-1" size="large">登录你滴账号 (*^▽^*)┛</el-text>
            </el-form-item>

            <el-form-item label="邮箱">
                <el-input v-model="userData.user.email" />
            </el-form-item>

            <el-form-item label="密码">
                <el-input v-model="userData.user.password" type="password" />
            </el-form-item>


            <el-row :gutter="20" v-if="userData.failNumber >= 3" class="verify-code-row">
                <el-col :span="12">
                    <el-form-item label="验证码">
                        <el-input v-model="userData.code" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-image style="width: 100px; height: 50px" :src="config.path" :fit="fit" @click="refreshCodeImg" />
                </el-col>
            </el-row>

            <el-form-item>
                <el-button type="primary" @click="login" :disabled="config.loginButtonDisponible"
                    style="width: 100%;">登录</el-button>
            </el-form-item>

            <el-form-item>
                还没有账号? <el-link @click="register" type="success">立即注册</el-link>
                
                <el-link @click="findPassowrd" type="error" style="margin-left: 20%;"> 
                        我忘记了我的密码!
                </el-link>
           
            </el-form-item>

        </div>
    </el-form>


    <el-dialog v-model="config.centerDialogVisible" title="验证" width="30%" align-center>
        <p><span>您使用了一个新的ip进行登录您的账号,请验证邮箱后继续</span></p>
        邮箱验证码:<el-input v-model="userData.emailCode" type="text"
            style="width: 100px; margin-right: 10px; margin-left: 10px;" />
        <el-button type="primary" @click="sendLoginEmailCode" :disabled="config.sendLoginEmailCodeButtonDisponible">
            {{ config.sendLoginEmailCodeButtonText }}
        </el-button>
        <template #footer>
            <span class="dialog-footer">

                <el-button type="primary" @click="login">
                    确认
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>


import { useRouter } from 'vue-router'
import { reactive, onMounted } from 'vue'
import { useStore } from 'vuex';
import _store from "@/store"

import StringUtil from '../../utils/StringUtil.js'
import InfoUtil from '../../utils/InfoUtil.js'
import RequestUtil from '../../utils/RequestUtil.js'


export default {
    props: ['changeShow'],
    setup(props) {
        onMounted(() => {
            let registerSuccessEmail = localStorage.getItem("userEmail");
            if (registerSuccessEmail != undefined && registerSuccessEmail != null && registerSuccessEmail != '') {
                userData.user.email = registerSuccessEmail;
            }
        })
        const store = useStore() || _store;
        const router = useRouter();
        //登录按钮点击
        const login = () => {

            if (StringUtil.isEmpty(userData.user.email) || StringUtil.isEmpty(userData.user.password)) {
                InfoUtil.warning("账号或密码不能为空")
                return;
            }
            if (!StringUtil.checkEmail(userData.user.email)) {
                InfoUtil.warning("邮箱格式不正确")
                return;
            }
            if (userData.user.password.length < 8 || userData.user.password.length > 30) {
                InfoUtil.warning("密码长度应在8-30位之间")
                return;
            }
            if (userData.failNumber >= 3 && StringUtil.isEmpty(userData.code)) {
                InfoUtil.warning("验证码不为空")
                return;
            }
            //禁用登录按钮
            config.loginButtonDisponible = true;
            RequestUtil.sendPostRequest("/user/login", userData).then(
                (res) => {
                    if (res.code == 200) {
                        localStorage.setItem("token", res.data)
                        router.push('/home');
                        return;
                    } else {
                        //新ip登录
                        if (res.data == "newIpLogin") {
                            config.centerDialogVisible = true;
                        } else {
                            InfoUtil.warning(res.message)
                            userData.failNumber = res.data;
                        }

                    }
                    //失败后刷新验证码
                    if (userData.failNumber >= 3) {
                        userData.code = "";
                        refreshCodeImg();
                    }
                    config.loginButtonDisponible = false;
                },
                (error) => {
                    config.loginButtonDisponible = false;
                    InfoUtil.error("请求失败")
                    return;
                }
            );
        }
        //刷新验证码图片
        const refreshCodeImg = () => {
            RequestUtil.sendGetRequestGetImage("/user/createLoginCode",  {"email":userData.user.email}).then(
                (res) => {
                    if(res!=null){
                        config.path = res;
                    }else{
                        config.path=require("../../assets/img/index/tooManyRequestCodeImg.jpg")
                    }
                },
                (err) => {
                    InfoUtil.error("请求失败")
                }
            );
        }

        //发送登录邮件验证码
        const sendLoginEmailCode = () => {
            config.sendLoginEmailCodeButtonDisponible = true;
            RequestUtil.sendGetRequest("/user/createLoginEmailCode", { "email": userData.user.email }).then(
                (res) => {
                    if (res.code == 200) {
                        InfoUtil.success(res.message);

                        localStorage.setItem("sendLoginEmailCodeTime", Date.now());
                        let sendEmailCodeInterval = setInterval(() => {
                            let time = Date.now() - localStorage.getItem("sendLoginEmailCodeTime");
                            //获取秒数
                            time /= 1000;
                            //验证码还在有效期内
                            if (300 > time) {
                                config.sendLoginEmailCodeButtonText = Math.ceil(300 - time) + "秒";
                            } else {
                                config.sendLoginEmailCodeButtonDisponible = false;
                                config.sendLoginEmailCodeButtonText = "发送登录邮箱验证码"
                                shutDownInterval();
                            }
                        }, 1000);
                        config.sendEmailCodeInterval = sendEmailCodeInterval;
                    } else {
                        InfoUtil.warning(res.message)
                    }
                },
                (err) => {
                    InfoUtil.error("发送验证码失败")
                    config.sendLoginEmailCodeButtonDisponible = false;
                }
            );
        }
        //关闭定时器
        const shutDownInterval = () => {
            let interval = config.sendEmailCodeInterval;
            if (interval != null) {
                window.clearInterval(interval);
                config.sendEmailCodeInterval = null;
            }
        }

        const register = () => {
            props.changeShow(1);
        }
        const findPassowrd=()=>{
            props.changeShow(3);
        }

        const config = reactive({
            //图形验证码路径
            path: "",
            //登录按钮是否禁用
            loginButtonDisponible: false,
            //新ip登录验证码框是否展示
            centerDialogVisible: false,
            //发送登录邮箱验证码按钮上的文字
            sendLoginEmailCodeButtonText: "发送登录邮箱验证码",
            //发送登录邮箱验证码按钮是否禁用
            sendLoginEmailCodeButtonDisponible: false,
            sendEmailCodeInterval: null

        })

        const userData = reactive({
            user: {
                email: "",
                password: ""
            },
            code: "",
            emailCode: "",
            failNumber: 0
        })
        return {
            userData, config,
            refreshCodeImg, login, register, sendLoginEmailCode,findPassowrd
        }

    }


}
</script>

<style scoped>
.user-login-form {
    position: absolute;
    height: 35vh;
    width: 30vw;
    background-color: #f2f6fc;
    border-radius: 20px;
    top: calc(50vh - 17.5vh);
    left: 60vw;
}

.el-row {
    align-items: center;
}

.form-content {
    width: 80%;
    height: 80%;
    position: relative;
    top: 2vh;
    left: 10px;
}
</style>